from django.contrib import messages
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404
from django.views.generic import CreateView, TemplateView, ListView

from common.forms import SelectAssigneeForm
from common.mixins import UserCourseRelatedMixin, PageinatorMixin
from course.views import SidebarMixin
from course.models import Course
from user.contants import GROUP_STUDENT
from user.models import User
from task.models import Task
from .forms import (
    InterviewContentForm, InterviewForm, InterviewFinishForm,
)
from .models import Interview, InterviewContent


class InterviewCreateView(UserCourseRelatedMixin, SidebarMixin, CreateView):
    template_name = 'interview/create.html'
    section_title = 'create interview'

    form_class = InterviewForm
    select_assignee_form = None
    course_id = None

    student = None

    def get_success_url(self):
        return reverse('interview:update_contents',
                       kwargs={'interview_id': self.object.id,
                               'course_id': self.course_id})

    def dispatch(self, request, student_id, course_id):
        self.course_id = course_id
        self.student = get_object_or_404(User, id=student_id)
        self.select_assignee_form = SelectAssigneeForm()
        return super(InterviewCreateView, self).dispatch(
            request, student_id, course_id)

    def get_initial(self):
        return {
            'interviewee': self.student,
            'interviewer': self.request.user,
        }

    def form_valid(self, form):
        self.object = form.save()
        assignee = User.objects.get(id=self.request.POST['assign_to'])
        task = Task.objects.create(
            assignor=self.request.user,
            assignee=assignee,
            ttype=Task.INTERVIEW,
            interview=self.object,
        )
        task.save()
        return HttpResponseRedirect(self.get_success_url())


class InterviewContentsUpdateView(
        UserCourseRelatedMixin, SidebarMixin,
        TemplateView, PageinatorMixin):

    template_name = 'interview/update_contents.html'
    section_title = 'update contents'

    interview = None
    content_form = None
    is_student = False
    summary_form = None

    def dispatch(self, request, interview_id, course_id=None):
        self.interview = get_object_or_404(Interview, id=interview_id)
        self.content_form = InterviewContentForm()
        if course_id is not None:
            self.course = get_object_or_404(Course, id=course_id)
            self.course_id = course_id
        else:
            self.course_slug = 1
        if request.user.is_in_group(GROUP_STUDENT):
            self.is_student = True
        self.task = Task.objects.filter(
            ttype=Task.INTERVIEW, assignee=request.user,
            interview=self.interview).first()
        self.summary_form = InterviewFinishForm(instance=self.interview)

        return super(InterviewContentsUpdateView, self).dispatch(
            request, interview_id, course_id)

    def get(self, request, interview_id, course_id):
        # print('self.is_student', self.is_student)
        # print('self.task', self.task)
        return self.render_to_response({
            'view': self,
        })

    def post(self, request, interview_id, course_id):
        if 'question' in request.POST:
            form = InterviewContentForm(data=request.POST)
            if form.is_valid():
                interviewcontent = form.save(commit=False)
                interviewcontent.interview = self.interview
                interviewcontent.save()
                messages.success(request, 'content added successfully')
            else:
                messages.error(request, 'form validation failed')
        elif 'summary' in request.POST:
            form = InterviewFinishForm(data=request.POST,
                                       instance=self.interview)
            if form.is_valid():
                form.save()
                self.summary_form = form
                messages.success(request, 'summary updated successfully')
            else:
                messages.error(request, 'form validation failed')
        return self.render_to_response({
            'view': self,
        })


class InterviewStudentView(SidebarMixin, TemplateView):

    template_name = 'interview/student.html'

    interviews = None

    def dispatch(self, request):
        self.interviews = Interview.objects.filter(
            interviewee=request.user).order_by('-created_date')
        return super(InterviewStudentView, self).dispatch(
            request)

    def get(self, request):
        return self.render_to_response({
            'view': self,
        })


class InterviewClassView(
        UserCourseRelatedMixin, SidebarMixin,
        ListView, PageinatorMixin):

    course = None
    section_title = 'Manage Class Students'
    taskselect = None
    template_name = 'interview/class_view.html'
    context_object_name = 'user_list'

    @property
    def search_url(self):
        return 'interview:class_view'

    @property
    def search_url_para(self):
        return self.course.id

    def __init__(self, **kwargs):
        super(InterviewClassView, self).__init__(**kwargs)

    def dispatch(self, request, pk):
        self.course = get_object_or_404(Course, id=pk)
        self.course_id = pk
        self.taskselect = SelectAssigneeForm()
        return super(InterviewClassView, self).dispatch(request, pk)

    def get_queryset(self):
        queryset = self.course.students.all()
        queryset = super(InterviewClassView, self).filter_queryset(
            queryset)
        return queryset

    def render_to_response(self, context, **response_kwargs):
        return super(InterviewClassView, self).render_to_response(
            context, **response_kwargs
        )

    def get_context_data(self, **kwargs):
        context = super(InterviewClassView, self).get_context_data(**kwargs)

        q = self.request.GET.get('q')
        if q:
            context['q'] = q
        print("----", context)

        return context
